<template>
  <div class="form-container">
    <div class="form-breadcrumb">
      <el-breadcrumb separator-class="el-icon-arrow-right">
        <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
        <el-breadcrumb-item>优惠券管理</el-breadcrumb-item>
        <el-breadcrumb-item :to="{ path: '/couponList' }">优惠券列表</el-breadcrumb-item>
        <el-breadcrumb-item>编辑优惠券</el-breadcrumb-item>
      </el-breadcrumb>
    </div>
    <div class="form-content">

      <el-form ref="form" :model="form" :rules="rules" label-width="126px">
        <el-tabs v-model="activeName" @tab-click="handleClick">

          <el-tab-pane label="基本信息" name="first">
            <el-form-item label="排序">
              <el-col :span="5">
                <el-input v-model="form.sort" placeholder="数字越小越靠前"></el-input>
              </el-col>
              <el-col :span="5"><span style="padding-left: 5px;font-size: 12px;">数字越小越靠前</span></el-col>
            </el-form-item>
            <el-form-item label="优惠券名称" prop="name">
              <el-input v-model="form.name" placeholder="请输入优惠券名称"></el-input>
            </el-form-item>
            <el-form-item label="优惠券类型" prop="type">
              <el-select v-model="form.type" placeholder="请选择优惠券类型" @change="handleChange">
                <el-option label="普通" value="1"></el-option>
                <el-option label="上新" value="2"></el-option>
                <el-option label="爆款" value="3"></el-option>
                <el-option label="优选" value="4"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="使用条件" prop="condition">
              <el-col :span="6">
                <span v-if="form.condition == 0">不限制</span>
                <span v-else>消费满{{form.condition}}可用</span>
              </el-col>
            </el-form-item>
            <el-form-item label="使用时间限制">
              <el-row v-if="form.time_type == 1">
                <span>获得后{{form.date}}天内有效</span>
              </el-row>
              <el-row style="margin-top: 5px" v-if="form.time_type == 2">
                <span>{{form.useTimes[0]}}&nbsp;~&nbsp;{{form.useTimes[1]}}</span>
              </el-row>
            </el-form-item>
            <el-form-item label="优惠方式">
              <el-row>
                <span v-if="form.discount_type == '1'">立减{{form.discount_money}}元</span>
                <span v-if="form.discount_type == '2'">打折{{form.discount_money}}折</span>
                <span v-if="form.discount_type == '3'">返利{{form.discount_money}}元</span>
              </el-row>
            </el-form-item>
            <el-form-item label="发放总数" prop="num">
              <el-input v-model="form.num" placeholder="优惠券总数量，没有不能领取或发放-1为不限制张数"></el-input>
            </el-form-item>
            <el-form-item label="是否上架">
              <el-switch v-model="form.status"></el-switch>
            </el-form-item>
            <el-form-item>
              <el-row>
                <el-button type="danger" @click="confirmEdit('form')">立即保存</el-button>
                <el-button type="primary" @click="next('form','two')">下一步</el-button>
                <el-button type="default" @click="cancel()">返回列表</el-button>
              </el-row>
            </el-form-item>
          </el-tab-pane>

          <el-tab-pane label="使用限制" name="two">
            <el-form-item label="优惠使用限制">
              <el-radio v-model="form.rule_type" border size="small" label="1">无优惠使用限制</el-radio><br/>
              <el-radio v-model="form.rule_type" border size="small" label="2">不可与促销优惠同时使用</el-radio><br/>
              <el-radio v-model="form.rule_type" border size="small" label="3">不可与会员折扣同时使用</el-radio><br/>
              <el-radio v-model="form.rule_type" border size="small" label="4">不可与促销优惠和折扣同时使用</el-radio>
            </el-form-item>
            <el-form-item label="是否限制店铺">
              <el-row>
                <el-radio v-model="form.is_store" border size="small" label="0">不限制</el-radio>
                <el-radio v-model="form.is_store" border size="small" label="1">限制以下店铺</el-radio>
              </el-row>
              <el-row>
                <el-select filterable remote reserve-keyword :remote-method="_query_store" v-if="form.is_store=='1'"
                           v-model="form.store_lst"
                           multiple placeholder="请选择店铺" style="width: 100%">
                  <el-option
                    v-for="item in stores"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value">
                  </el-option>
                </el-select>
              </el-row>
            </el-form-item>
            <el-form-item label="商品分类使用限制">
              <el-row>
                <el-radio v-model="form.is_cate_limit" border size="small" label="0">不添加商品分类限制</el-radio>
                <el-radio v-model="form.is_cate_limit" border size="small" label="1">允许以下商品分类使用</el-radio>
              </el-row>
              <el-row>
                <el-select filterable remote reserve-keyword :remote-method="_query_cate" v-if="form.is_cate_limit=='1'"
                           v-model="form.cate_lst"
                           multiple placeholder="请选择商品分类" style="width: 100%">
                  <el-option
                    v-for="item in cates"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value">
                  </el-option>
                </el-select>
              </el-row>
            </el-form-item>
            <el-form-item label="商品使用限制">
              <el-row>
                <el-radio v-model="form.is_product_limit" border size="small" label="0">不添加商品限制</el-radio>
                <el-radio v-model="form.is_product_limit" border size="small" label="1">允许以下商品使用</el-radio>
              </el-row>
              <el-row>
                <el-select filterable remote reserve-keyword :remote-method="_query_good"
                           v-if="form.is_product_limit == '1'"
                           v-model="form.product_lst"
                           multiple placeholder="请选择商品" style="width: 100%">
                  <el-option
                    v-for="item in goods"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value">
                  </el-option>
                </el-select>
              </el-row>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="next('form','first')">上一步</el-button>
              <el-button type="danger" @click="confirmEdit('form')">保存</el-button>
              <el-button type="default" @click="cancel()">返回列表</el-button>
            </el-form-item>
          </el-tab-pane>

        </el-tabs>


      </el-form>
    </div>
  </div>

</template>

<script>

  export default {
    components: {},
    data() {
      return {
        validate: false,
        activeName: 'first',
        cates: [],
        goods: [],
        stores: [],
        form: {
          id: '',
          status: 0,
          is_store: '0',
          store_lst: '',
          cate_lst: '',
          product_lst: '',
          time_type: '1',
          useTimes: [],
          date: '',
          condition: '0',//使用条件
          discount_type: '1', //优惠方式 1立减 2打折
          discount_money: '',//优惠金额
          is_product_limit: '0', //商品限制
          rule_type: '1', //使用限制
          is_cate_limit: '0', //商品分类限制
          sort: 100,
          num: '',
          name: '',
          type: '',
          type_id:'',
        },
        rules: {
          name: [
            {required: true, message: '请输入优惠券名称', trigger: 'blur'},
          ],
          type: [
            {required: true, message: '请选择优惠券类型', trigger: 'blur'}
          ],
          num: [
            {required: true, message: '请输入优惠券发放总数', trigger: 'blur'},
          ],

        },
        filter_keyword: '',
        types: {1: '普通', 2: '上新', 3: '爆款', 4: '优选'},

      }
    },
    mounted() {
      this._init_data();
    },
    methods: {
      handleClick() {

      },
      handleChange(val){
        this.form.type_id = val;
      },
      _init_data() { //加载页面数据
        const id = this.$route.query.id;
        this.$http.get('/api/root/CouponShop/getCoupon', {id: id})
          .then(rest => {
            if (rest.data) {
              let {useTimes} = this.form;
              let {
                type, type_id,time_type, date, start_time, end_time, discount_type,
                rule_type, is_product_limit, is_cate_limit, is_store,
                product_lst, store_lst, cate_lst, condition, status,
                product_lst_array, store_lst_array, cate_lst_array
              } = rest.data;
              type_id = type;
              type = this.types[type];

              if (condition <= 0) {
                condition = 0;
              }
              if (time_type === 2) {
                start_time = this.$moment(start_time * 1000).format('yyyy-MM-DD');
                end_time = this.$moment(end_time * 1000).format('yyyy-MM-DD');
                useTimes.push(start_time);
                useTimes.push(end_time);
                date  = 0;
              }
              if (is_product_limit === 1 && product_lst) { //指定商品情况下
                product_lst = product_lst.split(",").map(function (item) {
                  return parseInt(item);
                });
                this.goods = product_lst_array;
              }
              if (is_store === 1 && store_lst) {
                store_lst = store_lst.split(",").map(function (item) {
                  return parseInt(item);
                });
                this.stores = store_lst_array;
              }
              if (is_cate_limit === 1 && cate_lst) {
                cate_lst = cate_lst.split(",").map(function (item) {
                  return parseInt(item);
                });
                this.cates = cate_lst_array;
              }
              status = status == 1;
              time_type = time_type ? time_type.toString() :'1';
              discount_type = discount_type ? discount_type.toString() : '1';
              rule_type = rule_type ? rule_type.toString() : '1';
              is_store = is_store ? is_store.toString() : '0';
              is_cate_limit = is_cate_limit ? is_cate_limit.toString() : '0';
              is_product_limit = is_product_limit ? is_product_limit.toString() : '0';

              this.form = {
                ...rest.data,
                type,
                type_id,
                time_type,
                date,
                useTimes,
                discount_type,
                rule_type,
                is_store,
                is_cate_limit,
                is_product_limit,
                product_lst,
                cate_lst,
                store_lst,
                condition,
                status,
              };
            }
          })
      },

      confirmEdit(form) {
        this.validateFormData(form);
        if (this.validate) {
          const {useTimes, product_lst, store_lst, cate_lst} = this.form;
          let startTime = this.$moment(useTimes[0]).format('YYYY-MM-DD');
          let endTime = this.$moment(useTimes[1]).format('YYYY-MM-DD');

          this.form.start_time = startTime;
          this.form.end_time = endTime;
          if (product_lst && Array.isArray(product_lst)) {
            console.log('product_lst',product_lst);
            this.form.product_lst = product_lst.join(",");
          }
          if (store_lst && Array.isArray(store_lst)) {
            console.log('store_lst',store_lst);
            this.form.store_lst = store_lst.join(",")
          }
          if (cate_lst && Array.isArray(cate_lst)) {
            console.log('cate_lst',cate_lst);
            this.form.cate_lst = cate_lst.join(",");
          }
          this.form.type = this.form.type_id; //处理优惠券类型
          const _ths = this;
          this.$http.post('/api/root/CouponShop/editCoupon', {...this.form})
            .then(rest => {
              if (rest.msg == 'ok') {
                this.$message.success('保存成功');
                setTimeout(function () {
                  _ths.$router.push({name: 'couponList'})
                }, 800)
              } else {
                this.$message.error(rest.msg);
              }
            })
        }
      },
      cancel() {
        this.$router.push({name: 'couponList'})
      },

      next(form, next) {
        this.validateFormData(form);
        if (this.validate) {
          this.activeName = next;
        }
      },
      prev(val) {
        this.activeName = val;
      },
      _query_cate(query) {
        let api = '/api/root/cate/choice';
        this._query_api(api, query, 1);
      },
      _query_store(query) {
        let api = '/api/root/storeShop/choice';
        this._query_api(api, query, 2);
      },
      _query_good(query) {
        let api = '/api/root/ProductShop/getChoiceProductLst';
        this._query_api(api, query, 3);
      },
      _query_api(api, query, type) {
        this.$http.get(api, {keyword: query}).then(rest => {
          if (rest.code == 1) {
            switch (type) {
              case 3:
                this.goods = rest.data;
              case 2:
                this.stores = rest.data;
              case 1:
                this.cates = rest.data;
            }
          }
        });
      },
      /**
       * 验证表单数据
       * @param form
       */
      validateFormData(form) {
        this.$refs[form].validate((valid) => {
          if (!valid) {
            this.$message({
              message: '表单数据未填写完整,操作失败！',
              type: 'warning'
            });
            return false;
          }
          this.validate = true;
          return true;
        })
      },

    }
  }
</script>
<style lang="less" scoped>
  @import "index.less";
</style>